(function (doc) {
  var oInput = doc.getElementById('J_searchInput'),
    searchItemTpl = doc.getElementById('J_searchItemTpl').innerHTML,
    oList = doc.getElementById('J_list');

  function musicSearch(e) {
    var keyword = trimSpace(e.target.value),
      len = keyword.length;

    if (len > 0) {
      dataRequest(keyword, 10);
    } else {
      showList(false);
    }
  }

  function dataRequest(keyword, musicCount) {
    //目前api 失效
    xhr.ajax({
      url: `https://api.douban.com/v2/music/search?q=${keyword}&count=${musicCount}`,
      type: 'GET',
      dataType: 'JSONP',
      jsonp: 'callback',
      success: function (data) {
        if (data && data.musics.length > 0) {
          renderList(data.musics);
        }
      }
    });
  }

  function renderList(data) {
    var list = '';
    data.forEach(function (elem) {
      list += searchItemTpl.replace(/\{\{(.*?)\}\}/g, function (node, key) {
        return {
          url: elem.alt,
          image: elem.image,
          title: elem.alt_title || elem.attrs.title[0],
          singer: elem.attrs.singer ? elem.attrs.singer[0] : ''
        }[key];
      });
    });

    oList.innerHTML = list;
    showList(true);
  }

  function showList(show) {
    if (show) {
      oList.style.display = 'block';
    } else {
      oList.innerHTML = '';
      oList.style.display = 'none';
    }
  }

  function bindEvent() {
    oInput.addEventListener('input', musicSearch, false);
  }

  function init() {
    bindEvent();
  }

  init();
})(document);
